<script>
import Vue from 'vue';
import Ws from '@/common/js/ws.js';
import DB from '@/common/js/db.js';
import { mapMutations } from 'vuex';
export default {
	data() {
		return {
			globalData:{
				ws:null
			}
		};
	},
	onLaunch: function() {
		if (process.env.NODE_ENV === 'development') {
			console.log('开发环境');
			// #ifdef  H5
			this.$store.commit('setBaseUrl', 'http://122.51.141.95:8080');
			this.$store.commit('setWsUrl', 'wss://huoyuchuan.xyz:8889');
			this.$request.setConfig({
				baseUrl: this.$store.state.baseUrl // 此为测试地址，需加入到域名白名单，或者更改为您自己的线上地址即可
			});
			// #endif
		} else {
			console.log('生产环境');
		}
		uni.getSystemInfo({
			success: function(e) {
				// #ifndef MP
				Vue.prototype.StatusBar = e.statusBarHeight;
				if (e.platform == 'android') {
					Vue.prototype.CustomBar = e.statusBarHeight + 50;
				} else {
					Vue.prototype.CustomBar = e.statusBarHeight + 45;
				}
				// #endif

				// #ifdef MP-WEIXIN
				Vue.prototype.StatusBar = e.statusBarHeight;
				let custom = wx.getMenuButtonBoundingClientRect();
				Vue.prototype.Custom = custom;
				Vue.prototype.CustomBar = custom.bottom + custom.top - e.statusBarHeight;
				// #endif

				// #ifdef MP-ALIPAY
				Vue.prototype.StatusBar = e.statusBarHeight;
				Vue.prototype.CustomBar = e.statusBarHeight + e.titleBarHeight;
				// #endif
			}
		});
		let token = uni.getStorageSync(this.GLOBAL.CacheKeys.token);
		if (this.isNotBlank(token)) {
			this.$request.setConfig({
				header: {
					token: token,
					'content-type': 'application/json'
				}
			});
			this.$store.state.hasLogin = true;
			this.$store.state.userInfo = uni.getStorageSync(this.GLOBAL.CacheKeys.userInfo);
		}
		// #ifndef  H5
		Vue.prototype.db = new DB('msg', 'openThree.db');
		console.log(this.db.isOpen(), 'db open');
		this.db.executeSQL(this.GLOBAL.Sql.createIndex);
		this.db.executeSQL(this.GLOBAL.Sql.createMessage);
		this.db.executeSQL(this.GLOBAL.Sql.createRcontact);
		// #endif
	},
	watch: {
		'$store.state.hasLogin': {
			handler(val, old) {
				console.log(val, 'App watch');
				if (val == 'reLogin'&&this.$store.state.retryLoginCur<=this.$store.state.retryLoginMax) {
					if (this.ws) this.ws.closeWs();
					this.$store.state.hasLogin = true;
					this.$store.state.retryLoginCur+=1
					return;
				}else{
					setTimeout(() => {
						this.$store.state.retryLoginCur = 1;
					}, 60000)
				}
				if (!val) {
					if (this.ws) this.ws.closeWs();
					return;
				}
				this.rcontactSyncInc(); //联系人增量同步
				Vue.prototype.ws =new Ws(this.$store.state.wsUrl, this.$request.getConfig().header.token);
				this.globalData.ws=Vue.prototype.ws;
				this.ws.socketTask.onMessage(
					async function(res) {
						console.log('onMessage:' + res.data);
						var json = JSON.parse(res.data);
						if (json.command == 13) return;
						// #ifndef  H5
						await this.analysis(json);
						this.$store.state.onMessage = true; //异步必须等updateCount执行完成
						// #endif
					}.bind(this)
				);
			}
		}
	},
	onShow() {
		console.log('App Show');
		this.$store.state.hasLogin = true;
	},
	onHide() {
		console.log('App Hide');
		this.$store.state.hasLogin = false;
	},
	methods: {
		...mapMutations(['logout']),
		async analysis(json) {
			let flag = false;
			//插入在线消息
			if (json.command === 11 && json.data != undefined) {
				await this.insertMsg(json.data, this);
				flag = true;
			}
			//插入离线消息
			if (json.command === 20 && json.data != undefined) {
				//离线好友消息
				let friends = json.data.friends;
				for (var key in friends) {
					//for…of：是ES6定义的新的遍历数组的方法 直接返回数组元素
					for (var data of friends[key]) {
						await this.insertMsg(data, this);
					}
					flag = true;
				}
			}
			return flag;
		},
		//联系人单条同步
		rcontactSync(data) {
			if (data.cmd != 1) return;
			let insertRcontact =
				'insert or replace into  rcontact (userId, friendId,group_id,updateDttm,friendNickName,friendMobile)  ' +
				(
					"VALUES ('{to}', '{from}','{group_id}','" +
					this.moment(data.createTime).format('YYYY-MM-DD hh:mm:ss') +
					"','{extras.friendNickName}','{extras.friendMobile}');"
				).format(data);
			this.db.executeSQL(insertRcontact);
		},
		//联系人增量同步
		async rcontactSyncInc() {
			let userId = this.$store.state.userInfo.userId;
			if(userId==undefined){
				this.logout();
				return;
			}
			let selectLastUpdateTime = "select MAX(updateDttm) as lastUpdateTime from rcontact where userId='{0}'".format(userId);
			let lastUpdateTime = '1991-01-01 00:00:00';
			// #ifndef  H5
			let datas = await this.db.selectSQLSync(selectLastUpdateTime);
			if (this.isNotBlank(datas) && this.isNotBlank(datas[0].lastUpdateTime)) {
				lastUpdateTime = datas[0].lastUpdateTime;
			}
			// #endif
			let res = await this.$request.post('/user-admin/user/queryFriendsInc', {
				data: { userId: userId, updateDttm: lastUpdateTime }
			});
			for (let data of res.data) {
				let insertRcontact =
					'insert or replace into  rcontact (userId, friendId,group_id,updateDttm,friendNickName,friendMobile,portIsShow,portIsView,type)  ' +
					`VALUES ('${data.userId}', '${data.friendId}','${data.groupId}','${data.updateDttm}','${data.friendNickName}','${data.friendMobile}',${data.portIsShow},${data.portIsView},${data.type});`;
				// #ifndef  H5
				this.db.executeSQL(insertRcontact);
				// #endif
			}
		},
		async insertMsg(data, that) {
			this.rcontactSync(data);
			let roomId = data.from + '-' + data.to;
			if (data.chatType == 2 && !that.isNotBlank(data.group_id)) {
				data.group_id = roomId;
			}
			if(data.group_id==this.$store.state.currentRoom.id){
				this.$store.state.currentRoom.onMessage=true;
			}
			let sql =
				"INSERT INTO message (id,chatType,cmd,msgType,content,createTime,'from','to',group_id,extras,isRead) " +
				"VALUES ('{id}',{chatType},{cmd},{msgType},'{content}','{createTime}','{from}','{to}','{group_id}','{extras}',0);".format(data);
			that.db.executeSQL(sql);
			let selectCount = "SELECT count FROM 'index' WHERE \"from\"='{from}' and \"to\"='{to}' and \"group_id\"='{group_id}'".format(data);
			let datas = await that.db.selectSQLSync(selectCount);
			let count = 1;
			if (datas.length > 0) {
				count = datas[0].count + 1;
			}
			let insertIndex = (
				"insert or replace into 'index' (chatType,content,createTime,'from','to',group_id,extras,msgType,userId,count) " +
				"VALUES ({chatType},'{content}','{createTime}','{from}','{to}','{group_id}','{extras}','{msgType}','"+that.$store.state.userInfo.userId+"'," +
				count +
				') '
			).format(data);
			that.db.executeSQL(insertIndex);
		}
	}
};
</script>

<style>
@import 'components/colorui/main.css';
@import 'components/colorui/icon.css';
.uni-tag--disabled {
	pointer-events: none;
}
.status_bar {
	height: var(--status-bar-height);
	width: 100%;
}

.nav-list {
	display: flex;
	flex-wrap: wrap;
	padding: 0px 40upx 0px;
	justify-content: space-between;
}

.nav-li {
	padding: 30upx;
	border-radius: 12upx;
	width: 45%;
	margin: 0 2.5% 40upx;
	background-image: url(https://cdn.nlark.com/yuque/0/2019/png/280374/1552996358352-assets/web-upload/cc3b1807-c684-4b83-8f80-80e5b8a6b975.png);
	background-size: cover;
	background-position: center;
	position: relative;
	z-index: 1;
}

.nav-li::after {
	content: '';
	position: absolute;
	z-index: -1;
	background-color: inherit;
	width: 100%;
	height: 100%;
	left: 0;
	bottom: -10%;
	border-radius: 10upx;
	opacity: 0.2;
	transform: scale(0.9, 0.9);
}

.nav-li.cur {
	color: #fff;
	background: rgb(94, 185, 94);
	box-shadow: 4upx 4upx 6upx rgba(94, 185, 94, 0.4);
}

.nav-title {
	font-size: 32upx;
	font-weight: 300;
}

.nav-title::first-letter {
	font-size: 40upx;
	margin-right: 4upx;
}

.nav-name {
	font-size: 28upx;
	text-transform: Capitalize;
	margin-top: 20upx;
	position: relative;
}

.nav-name::before {
	content: '';
	position: absolute;
	display: block;
	width: 40upx;
	height: 6upx;
	background: #fff;
	bottom: 0;
	right: 0;
	opacity: 0.5;
}

.nav-name::after {
	content: '';
	position: absolute;
	display: block;
	width: 100upx;
	height: 1px;
	background: #fff;
	bottom: 0;
	right: 40upx;
	opacity: 0.3;
}

.nav-name::first-letter {
	font-weight: bold;
	font-size: 36upx;
	margin-right: 1px;
}

.nav-li text {
	position: absolute;
	right: 30upx;
	top: 30upx;
	font-size: 52upx;
	width: 60upx;
	height: 60upx;
	text-align: center;
	line-height: 60upx;
}

.text-light {
	font-weight: 300;
}

@keyframes show {
	0% {
		transform: translateY(-50px);
	}

	60% {
		transform: translateY(40upx);
	}

	100% {
		transform: translateY(0px);
	}
}

@-webkit-keyframes show {
	0% {
		transform: translateY(-50px);
	}

	60% {
		transform: translateY(40upx);
	}

	100% {
		transform: translateY(0px);
	}
}
</style>
